import { Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { Events } from 'ionic-angular';



//聊天用户信息
export class ChartMessage {
  messageId: string;
  userId: string;
  username: string;
  userImgUrl: string;
  toUserId: string;
  time: number | string;
  message: string;
  status: string;
}
//用户信息
export class UserInfo {
  userId: string;
  username: string;
  userImgUrl: string;
}

@Injectable()
export class ChatserviceProvider {


  constructor(
    public http: Http,
    public events:Events) {
  }

  /**
   * 
   * 获取消息列表
   * 
   * @returns {Promise<ChartMessage[]>} 
   * @memberof ChatserviceProvider
   */
  getMessageList(): Promise<ChartMessage[]> {
    const url = '../../assets/mock/msg-list.json';
    return this.http.get(url)
      .toPromise()
      .then(response => response.json().array as ChartMessage[])
      .catch(error => Promise.reject(error || '错误信息'));
  }

  sendMessage(message: ChartMessage) {
    return new Promise(resolve => setTimeout(() => {
      resolve(message)
    }, Math.random() * 100))
      .then(() => {
        this.mockNewMessage(message);
      })
  }

  /**
   * 
   * 模拟对方发送了消息
   * 引入Events
   * @param {*} message 
   * @memberof ChatserviceProvider
   */
  mockNewMessage(message: any) {
    const id = Date.now().toString();
    let messageSend: ChartMessage = {
      messageId: id,
      userId: '123321',
      username: '女神',
      userImgUrl: 'http://img.mukewang.com/user/57a322f00001e4ae02560256-40-40.jpg',
      toUserId: message.userId,
      time: Date.now(),
      message: `您是不是给我发送了${message.message}`,
      status: 'success'
    }
    setTimeout(()=>{
      this.events.publish('chat.recevied',messageSend,Date.now());
    },Math.random()*1000)
  }

}
